<?php

namespace app\mp\controller;

use app\BaseController;
use app\common\exception\AuthException;
use Firebase\JWT\JWT;
use think\App;
use think\facade\Db;
use think\facade\Env;

class Base extends BaseController
{

    //登录的用户 目前数据库中 用户和微信用户是分开的
    protected $user;
    /**
     * dev环境变量
     * @var string
     */
    protected $environDev = 'dev';

    public function __construct(App $app)
    {
        parent::__construct($app);
        $request = request();
        $jwtKey = env('jwt.key');
        $token = $request->header("token");
        /**
         * 添加dev判断，不走校验
         */
        if ($this->isDev()) {
            $this->user = [
                'id' => 42
            ];
        } else {
            if (empty($token)) {
                throw new AuthException("没有登录");
            }
            try {
                $payload = JWT::decode($token, $jwtKey, array('HS256'));
                if ($payload) {
                    //检测登录时间 是否过期
                    if ($payload->exp < time()) {
                        throw new AuthException("没有登录");
                    }
                    $this->collectUserInfo($payload->id, $payload->exp);
                } else {
                    throw new AuthException("没有登录");
                }
            } catch (\Exception $e) {
                throw $e;
            }
        }
    }

    /**
     * 开发环境判断
     * @return bool
     */
    protected function isDev()
    {
        $environ = Env::get('local.environ') ?? 'production';
        return $environ == $this->environDev;
    }

    private function collectUserInfo($userId, $expireTime)
    {
        $this->user = Db::table("wechat_user")->where(['id' => $userId])->find();
    }
}